package com.platform.dahuatech.icc.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.dahuatech.hutool.http.Method;
import com.dahuatech.icc.exception.ClientException;
import com.dahuatech.icc.oauth.http.DefaultClient;
import com.dahuatech.icc.oauth.http.IClient;
import com.dahuatech.icc.oauth.http.IccHttpHttpRequest;
import com.dahuatech.icc.oauth.http.IccTokenResponse;
import com.dahuatech.icc.oauth.model.v202010.GeneralRequest;
import com.dahuatech.icc.oauth.profile.IccProfile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.platform.dahuatech.icc.entity.*;
import com.platform.dahuatech.icc.service.DaHuatechIccPlatformService;
import common.core.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author 贾伟焘
 * @version 1.0
 * @Description TODO
 * @Date 2022/7/8 9:58
 */
@Slf4j
@Service
public class DaHuatechIccPlatformServiceImpl implements DaHuatechIccPlatformService {

    private final ObjectMapper mapper = new ObjectMapper();

    @Resource
    private IClient iClient;

    /**
     * 获取大华ICC平台通道号信息
     */
    @Override
    public JSONResult getPlatformChannelInfo() throws ClientException, JsonProcessingException {
        List<ExportDeviceChannelInformation> list = new ArrayList<>();
        recursionDeviceTree("/evo-apigw/evo-brm/1.2.0/tree", "/evo-apigw/evo-brm/1.0.0/device/", list, "", 0);
        String fileNamePath = System.getProperty("user.dir") + File.separator + DateUtil.format(new DateTime(), "yyyyMMddHHmmss") + "--" + IdUtil.fastSimpleUUID() + ".xlsx";
        EasyExcel.write(fileNamePath, ExportDeviceChannelInformation.class).sheet("大华ICC平台通道号").doWrite(list);
        log.info("生成完成");
        return JSONResult.ok();
    }

    /**
     * 设备树递归
     */
    private JSONResult recursionDeviceTree(String deviceTreePath, String deviceDetailPath, List<ExportDeviceChannelInformation> list, String body, int checkStat) throws ClientException, JsonProcessingException {
        IccHttpHttpRequest iccHttpHttpRequest = new IccHttpHttpRequest(IccProfile.URL_SCHEME + deviceTreePath, Method.POST);
        if (StrUtil.isEmpty(body)) {
            iccHttpHttpRequest.setBody(new JSONObject().putOpt("type", "001;1;1").toString());
        } else {
            iccHttpHttpRequest.setBody(new JSONObject().putOpt("id", body).putOpt("type", body + ";1;1").putOpt("checkStat", checkStat).toString());
        }
        String deviceTreeResponse = iClient.doAction(iccHttpHttpRequest);
        JSONObject deviceTreeObj = JSONUtil.parseObj(deviceTreeResponse);
        if (deviceTreeObj.getInt("code") != 0) {
            return JSONResult.errorMsg("查询设备树错误，错误代码：" + deviceTreeObj.getInt("code"));
        }
        String data = deviceTreeObj.getStr("data");
        JSONObject jsonObject = JSONUtil.parseObj(data);
        JSONArray value = JSONUtil.parseArray(jsonObject.getStr("value"));
        List<DeviceTree> deviceTrees = JSONUtil.toList(value, DeviceTree.class);
        if (deviceTrees.isEmpty()) {
            return JSONResult.errorMsg("无数据");
        }
        for (DeviceTree deviceTree : deviceTrees) {
            if (ObjectUtil.isNotNull(deviceTree.getDeviceCode())) {
                getDaHuatechIccPlatformDetailInfo(deviceDetailPath, deviceTree.getDeviceCode(), list, deviceTree.getCheckStat());
            }
            if (deviceTree.getIsParent()) {
                recursionDeviceTree(deviceTreePath, deviceDetailPath, list, deviceTree.getId(), deviceTree.getCheckStat());
            }
        }
        return JSONResult.ok();
    }


    /**
     * 根据设备id 获取详细的设备的通道号
     *
     * @param deviceDetailPath 请求路径
     * @param deviceCode       设备code
     * @param list             添加的集合
     * @param checkState       状态
     * @throws ClientException
     * @throws JsonProcessingException
     */
    public void getDaHuatechIccPlatformDetailInfo(String deviceDetailPath, String deviceCode, List<ExportDeviceChannelInformation> list, int checkState) throws ClientException, JsonProcessingException {
        IccHttpHttpRequest iccHttpHttpRequest = new IccHttpHttpRequest(IccProfile.URL_SCHEME + deviceDetailPath + "/" + deviceCode, Method.GET);
        JSONObject body = new JSONObject();
        String deviceDetailResponse = iClient.doAction(iccHttpHttpRequest);
        JSONObject parseObj = JSONUtil.parseObj(deviceDetailResponse);
        JsonNode readValue = mapper.readValue(deviceDetailResponse, JsonNode.class);
        if (parseObj.getInt("code") != 0) {
            log.error("获取设备详情错误信息：" + readValue.get("errMsg") + ",错误代码：" + readValue.get("code").asInt());
            return;
        }
        String data = parseObj.getStr("data");
        JSONObject jsonObject = JSONUtil.parseObj(data);
        JSONArray units = JSONUtil.parseArray(jsonObject.getStr("units"));
        List<DeviceUnits> deviceUnits = JSONUtil.toList(units, DeviceUnits.class);
        if (deviceUnits.isEmpty()) {
            return;
        }
        for (DeviceUnits deviceUnit : deviceUnits) {
            if (deviceUnit.getChannels().isEmpty()) {
                continue;
            }
            for (DeviceChannel deviceChannel : deviceUnit.getChannels()) {
                list.add(ExportDeviceChannelInformation.builder()
                        .channelCode(deviceChannel.getChannelCode())
                        .channelName(deviceChannel.getChannelName())
                        .gpsX(deviceChannel.getGpsX())
                        .gpsY(deviceChannel.getGpsY())
                        .build());
            }

        }

    }
}
